// src-tauri/src/trust_network.rs
use super::{TrustTree, GOD_PEER_ID, GOD_PUBLIC_KEY};

pub struct TrustNetwork {
    trust_tree: TrustTree,
    local_peer_id: String,
    local_certificate: Option<TrustCertificate>,
}

impl TrustNetwork {
    pub fn new(local_peer_id: String) -> Self {
        // 创建信任树，最大深度7，每个节点最多7个子节点
        let trust_tree = TrustTree::new(7, 7);
        
        Self {
            trust_tree,
            local_peer_id,
            local_certificate: None,
        }
    }

    pub fn initialize_network(&mut self) -> Result<(), String> {
        // 验证God Peer存在
        let god_cert = self.trust_tree.get_god_peer_certificate()
            .ok_or("God Peer certificate not found")?;

        println!("Trust network initialized with God Peer: {}", GOD_PEER_ID);
        println!("God Peer public key: {}", GOD_PUBLIC_KEY);

        Ok(())
    }

    pub fn join_as_trusted_peer(
        &mut self,
        parent_peer_id: String,
        local_public_key: String,
    ) -> Result<TrustCertificate, String> {
        // 在实际系统中，这里应该向parent_peer_id发送授权请求
        // 简化实现：模拟授权过程
        
        // 验证父节点存在且有效
        if !self.trust_tree.validate_issuer_chain(&parent_peer_id) {
            return Err("Parent peer is not in valid trust chain".to_string());
        }

        // 创建本地证书（在实际系统中应由父节点签发）
        let local_certificate = TrustCertificate {
            peer_id: self.local_peer_id.clone(),
            public_key: local_public_key,
            role: PeerRole::Trusted,
            trust_level: 1, // 简化：假设是第一级
            parent_peer_id: parent_peer_id.clone(),
            issued_by: parent_peer_id,
            issue_date: current_timestamp(),
            expiry_date: current_timestamp() + 180 * 24 * 60 * 60,
            signature: "simulated_signature".to_string(),
            max_subordinates: 7,
            current_subordinates: 0,
            is_active: true,
        };

        // 验证证书链
        if !self.trust_tree.validate_certificate_chain(&local_certificate) {
            return Err("Local certificate chain validation failed".to_string());
        }

        // 添加到信任树
        self.trust_tree.certificates.insert(self.local_peer_id.clone(), local_certificate.clone());
        self.local_certificate = Some(local_certificate.clone());

        Ok(local_certificate)
    }

    pub fn verify_peer_authorization(&self, peer_id: &str) -> bool {
        self.trust_tree.validate_issuer_chain(peer_id)
    }

    pub fn get_trust_level(&self) -> Option<u8> {
        self.local_certificate.as_ref().map(|cert| cert.trust_level)
    }

    pub fn can_authorize_subordinates(&self) -> bool {
        self.local_certificate.as_ref()
            .map(|cert| {
                cert.is_active && 
                cert.trust_level < self.trust_tree.max_depth &&
                cert.current_subordinates < cert.max_subordinates
            })
            .unwrap_or(false)
    }

    pub fn get_network_info(&self) -> NetworkInfo {
        let total_peers = self.trust_tree.certificates.len();
        let active_peers = self.trust_tree.certificates.values()
            .filter(|cert| cert.is_active)
            .count();

        NetworkInfo {
            god_peer_id: GOD_PEER_ID.to_string(),
            total_peers,
            active_peers,
            max_depth: self.trust_tree.max_depth,
            max_children: self.trust_tree.max_children_per_node,
        }
    }

    pub fn validate_content_approval(
        &self,
        content_hash: &str,
        approver_peer_id: &str,
    ) -> Result<(), String> {
        // 验证批准者是否在有效的信任链中
        if !self.verify_peer_authorization(approver_peer_id) {
            return Err("Approver is not in valid trust chain".to_string());
        }

        // 验证批准者证书是否有效
        let approver_cert = self.trust_tree.certificates.get(approver_peer_id)
            .ok_or("Approver certificate not found")?;

        if !approver_cert.is_active {
            return Err("Approver certificate is not active".to_string());
        }

        // 检查证书是否过期
        if current_timestamp() > approver_cert.expiry_date {
            return Err("Approver certificate has expired".to_string());
        }

        Ok(())
    }
}

#[derive(Serialize, Deserialize)]
pub struct NetworkInfo {
    pub god_peer_id: String,
    pub total_peers: usize,
    pub active_peers: usize,
    pub max_depth: u8,
    pub max_children: u8,
}